/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.controller;

import cn.webrx.mapper.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringVersion;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.Thymeleaf;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: mybatis2021 - Index
 * <p>Powered by webrx On 2021-07-19 16:39:46
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */
@Controller
public class Index {
    @Autowired
    private StudentMapper sm;

    @RequestMapping("/")
    public String home() {
        return "redirect:/1";
    }

    @RequestMapping("/{p}")
    public String index(Model m, @PathVariable("p") int p) {
        String ver = String.format("Spring(%s)-SpringMVC(%s)-Thymeleaf(%s)-Mybatis(%s)", SpringVersion.getVersion(), SpringVersion.getVersion(), Thymeleaf.getVersion(), "3.5.7");
        m.addAttribute("version", ver);

        System.out.println(sm.query());
        m.addAttribute("msg", "Hello World (SSM三大框架整合)");

        PageHelper.startPage(p, 1);
        PageInfo pi = PageInfo.of(sm.query());
        int pagecount = pi.getPages();
        int currpage = pi.getPageNum();

        int start = 1;
        int end = 5;
        if (currpage > 5) {
            start = currpage - 4;
            end = currpage + 1;

            if (end > pagecount) end = pagecount;
        }


        m.addAttribute("start", start);
        m.addAttribute("end", end);
        m.addAttribute("pagecount", pagecount);
        m.addAttribute("currpage", currpage);
        m.addAttribute("ss", pi.getList());
        m.addAttribute("user", "张三丰");


        return "index";
    }

    @RequestMapping("/index/delete/{id}")
    public String del(@PathVariable("id") int id) {
        if (sm.deleteById(id) > 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除成功");
        }
        return "redirect:/";
    }

    @GetMapping("/add")
    public String add() {
        return "add";
    }

    @PostMapping("/save")
    public String save(String name, String info) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("info", info);
        sm.add(map);
        return "redirect:/";
    }
}
